use:viewport
Posted on 2023-04-06 by
henrikvilhelmberglundThis is an example of use:viewport which will tell us when an element enters the viewport or leaves the viewport.
Hello world!
<script>
import viewport from "./useViewportAction";
</script>
<div style="height: 200px; background: red;" />
<div style="height: 200px; background: blue;" />
<div style="height: 200px; background: green;" />
<h1
use:viewport
on:enterViewport={() => console.log("entered viewport")}
on:exitViewport={() => console.log("exited viewport")}>
Hello world!
</h1>
<div style="height: 200px; background: red;" />
<div style="height: 200px; background: blue;" />
<div style="height: 200px; background: green;" />
<style>
</style>
An important thing here is the lazy initialization of the action. The IntersectionObserver is only created when it is needed . We also reuse the observer if we already have one. Without this this whole page broke. 🤯